<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧分类树 -->
      <el-col :span="6">
        <el-card>
          <div class="tree-header">
            <div class="tree-actions">
              <el-button type="primary" size="small" @click="showAddCategoryDialog(null)">
                <el-icon>
                  <Plus />
                </el-icon>新增
              </el-button>
              <el-button size="small" @click="refreshCategoryTree">
                <el-icon>
                  <Refresh />
                </el-icon>刷新
              </el-button>
            </div>
          </div>

          <el-tree ref="categoryTreeRef" :data="categoryTree" node-key="id" highlight-current :props="treeProps"
            :expand-on-click-node="false" :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick"
            v-loading="treeLoading">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="node-actions">
                  <el-button link type="primary" @click.stop="showAddCategoryDialog(data)">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-button>
                  <el-button link type="primary" @click.stop="showEditCategoryDialog(data)">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                  <el-button link type="danger" @click.stop="deleteCategory(data)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧方案列表 -->
      <el-col :span="18">
        <el-card>
          <div class="table-header">
            <el-input v-model="queryParams.solutionNameOrCode" placeholder="请输入方案名称或编号" style="width: 300px" clearable
              @clear="handleQuery" @keyup.enter="handleQuery">
              <template #append>
                <el-button :icon="Search" @click="handleQuery" />
              </template>
            </el-input>

            <div class="table-actions">
              <el-button type="primary" @click="showAddSolutionDialog">
                <el-icon>
                  <Plus />
                </el-icon>新增方案
              </el-button>
              <!-- <el-button @click="showImportDialog">
                <el-icon>
                  <Upload />
                </el-icon>导入
              </el-button>
              <el-button @click="handleExport">
                <el-icon>
                  <Download />
                </el-icon>导出
              </el-button> -->
            </div>
          </div>

          <el-table :data="solutionList" border style="width: 100%" v-loading="tableLoading"
            :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
            <el-table-column prop="solutionId" label="方案编号" />
            <el-table-column prop="solutionName" label="方案名称" />
            <el-table-column prop="creator" label="创建人" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="来源">
              <template #default="{ row }">
                {{ getSourceTypeLabel(row.sourceType) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="showSolutionDetail(row)">详情</el-button>
                <el-button size="small" type="primary" @click="showEditSolutionDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteSolution(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog v-model="categoryDialogVisible" :title="categoryDialogTitle" width="40%" :close-on-click-modal="false"
      @closed="resetCurrentCategory">
      <el-form :model="currentCategory" label-width="100px" :rules="categoryRules" ref="categoryFormRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="currentCategory.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select v-model="currentCategory.parentId" :data="categoryTree" :props="treeProps" check-strictly
            placeholder="请选择父级分类" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCategory">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑方案对话框 -->
    <el-dialog v-model="solutionDialogVisible" :title="solutionDialogTitle" width="60%" :close-on-click-modal="false"
      @closed="handleDialogClose">
      <el-form :model="currentSolution" label-width="120px" :rules="solutionRules" ref="solutionFormRef">
        <el-form-item label="方案名称" prop="solutionName">
          <el-input v-model="currentSolution.solutionName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="directoryId">
          <el-tree-select v-model="currentSolution.directoryId" :data="categoryTree" :props="treeProps" check-strictly
            placeholder="请选择所属分类" style="width: 100%" />
        </el-form-item>
        <el-form-item label="适用场景" prop="applicableScenario">
          <el-input v-model="currentSolution.applicableScenario" type="textarea" :rows="3" placeholder="请输入适用场景描述" />
        </el-form-item>
        <el-form-item label="方案内容" prop="solutionContent">
          <el-input v-model="currentSolution.solutionContent" type="textarea" :rows="6" placeholder="请输入详细方案内容" />
        </el-form-item>
        <el-form-item label="附件">
          <!-- <el-upload action="" :file-list="fileList" :auto-upload="false" :on-change="handleFileChange" multiple
            :before-upload="beforeUpload">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片、文档等附件，单个文件不超过10MB
              </div>
            </template>
          </el-upload> -->
          <UploadFile v-model:file-ids="currentSolution.files" :fileList="currentSolution.filesList" type="file" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="solutionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSolution">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 方案详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="detailDialogTitle" width="70%" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="方案编号">{{ currentSolution.solutionCode }}</el-descriptions-item>
        <el-descriptions-item label="方案名称">{{ currentSolution.solutionName }}</el-descriptions-item>
        <el-descriptions-item label="所属分类">{{ getCategoryName(currentSolution.directoryId) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ currentSolution.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentSolution.createTime }}</el-descriptions-item>
        <el-descriptions-item label="来源">{{ getSourceTypeLabel(currentSolution.sourceType) }}</el-descriptions-item>
        <el-descriptions-item label="适用场景" :span="2">
          {{ currentSolution.applicableScenario }}
        </el-descriptions-item>
        <el-descriptions-item label="方案内容" :span="2">
          <div class="solution-content">{{ currentSolution.solutionContent }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="附件" :span="2">
          <div v-for="file in currentSolution.filesList" :key="file.fileId" class="file-item">
            <el-link type="primary" :href="file.filePath" target="_blank">
              {{ file.originalFileName }}
            </el-link>
            <span class="file-size">({{ formatFileSize(file.fileSize) }})</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入方案" width="40%" :close-on-click-modal="false">
      <el-upload class="upload-demo" drag action="" :auto-upload="false" :on-change="handleImportFileChange"
        :file-list="importFileList" accept=".xlsx,.xls">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件，文件大小不超过10MB
            <el-button type="text" @click="downloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, Upload, Download, UploadFilled, Edit, Delete } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'
import {
  getSolutionCategoryTree,
  addSolutionCategory,
  updateSolutionCategory,
  deleteSolutionCategory,
  getSolutionList,
  getSolutionDetail,
  addSolution,
  updateSolution,
  deleteSolution,
} from '@/api/dispatch/affair/scheme_library'

// 加载状态
const treeLoading = ref(false)
const tableLoading = ref(false)

// 分类树数据
const categoryTree = ref([])
const defaultExpandedKeys = ref([])
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 方案列表数据
const solutionList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  solutionNameOrCode: '',
  directoryId: ''
})

// 当前选中的分类
const currentCategoryId = ref('')

// 当前操作的分类
const currentCategory = reactive({
  id: '',
  name: '',
  parentId: ''
})

// 当前操作的方案
const currentSolution = reactive({
  solutionId: '',
  solutionName: '',
  solutionCode: '',
  directoryId: '',
  applicableScenario: '',
  solutionContent: '',
  files: '',
  filesList: []
})

// 文件列表
const fileList = ref([])
const importFileList = ref([])
const importFile = ref(null)

// 对话框控制
const categoryDialogVisible = ref(false)
const categoryDialogTitle = ref('新增分类')
const solutionDialogVisible = ref(false)
const solutionDialogTitle = ref('新增方案')
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('方案详情')
const importDialogVisible = ref(false)

// 表单引用
const categoryFormRef = ref(null)
const solutionFormRef = ref(null)

// 表单验证规则
const categoryRules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ]
})

const solutionRules = reactive({
  solutionName: [
    { required: true, message: '请输入方案名称', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  directoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  applicableScenario: [
    { required: true, message: '请输入适用场景', trigger: 'blur' },
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  solutionContent: [
    { required: true, message: '请输入方案内容', trigger: 'blur' },
    { min: 10, message: '至少输入10个字符', trigger: 'blur' }
  ]
})

// 来源类型映射
const sourceTypeMap = {
  1: '手动录入',
  2: '调度日志',
  3: '调度经验'
}

// 初始化数据
const initData = async () => {
  try {
    await fetchCategoryTree()
    await fetchSolutionList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取分类树
const fetchCategoryTree = async () => {
  try {
    treeLoading.value = true
    const res = await getSolutionCategoryTree()
    categoryTree.value = res.data
    // 默认展开第一级节点
    if (categoryTree.value.length > 0) {
      defaultExpandedKeys.value = [categoryTree.value[0].id]
    }
  } catch (error) {
    console.error('获取分类树失败:', error)
    ElMessage.error('获取分类树失败')
  } finally {
    treeLoading.value = false
  }
}

// 获取方案列表
const fetchSolutionList = async () => {
  try {
    console.log(queryParams);
    
    if(!queryParams.directoryId) return;
    tableLoading.value = true
    const res = await getSolutionList(queryParams)
    solutionList.value = res.rows
    total.value = res.total
    // 如果当前页无数据且不是第一页，则返回上一页
    if (solutionList.value.length === 0 && queryParams.pageNum > 1) {
      queryParams.pageNum -= 1
      await fetchSolutionList()
    }
  } catch (error) {
    console.error('获取方案列表失败:', error)
    ElMessage.error('获取方案列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理分类树节点点击
const handleNodeClick = (data) => {
  currentCategoryId.value = data.id
  queryParams.directoryId = data.id
  queryParams.pageNum = 1
  fetchSolutionList()
}

// 显示新增分类对话框
const showAddCategoryDialog = (parentData) => {
  categoryDialogTitle.value = '新增分类'
  currentCategory.id = ''
  currentCategory.name = ''
  currentCategory.parentId = parentData ? parentData.id : ''
  categoryDialogVisible.value = true
}

// 显示编辑分类对话框
const showEditCategoryDialog = (data) => {
  categoryDialogTitle.value = '编辑分类'
  currentCategory.id = data.id
  currentCategory.name = data.name
  currentCategory.parentId = data.parentId
  categoryDialogVisible.value = true
}

// 重置当前分类
const resetCurrentCategory = () => {
  currentCategory.id = ''
  currentCategory.name = ''
  currentCategory.parentId = ''
}

// 确认保存分类
const confirmCategory = async () => {
  try {
    await categoryFormRef.value.validate()

    if (categoryDialogTitle.value === '新增分类') {
      await addSolutionCategory(currentCategory)
      ElMessage.success('新增分类成功')
    } else {
      await updateSolutionCategory(currentCategory)
      ElMessage.success('修改分类成功')
    }

    categoryDialogVisible.value = false
    await fetchCategoryTree()
  } catch (error) {
    console.error('保存分类失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 删除分类
const deleteCategory = (data) => {
  ElMessageBox.confirm(`确认删除分类 "${data.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSolutionCategory(data.id)
      ElMessage.success('删除成功')
      await fetchCategoryTree()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 刷新分类树
const refreshCategoryTree = () => {
  fetchCategoryTree()
  ElMessage.success('刷新成功')
}

// 显示新增方案对话框
const showAddSolutionDialog = () => {
  solutionDialogTitle.value = '新增方案'
  resetCurrentSolution()
  solutionDialogVisible.value = true
}

// 显示编辑方案对话框
const showEditSolutionDialog = async (row) => {
  try {
    tableLoading.value = true
    const res = await getSolutionDetail(row.solutionId)
    console.log(res);

    Object.assign(currentSolution, res.data)
    currentSolution.filesList = currentSolution.filesList.map(item => ({ ...item ,name : item.originalFileName }))

    solutionDialogTitle.value = '编辑方案'
    solutionDialogVisible.value = true
  } catch (error) {
    console.error('获取方案详情失败:', error)
    ElMessage.error('获取方案详情失败')
  } finally {
    tableLoading.value = false
  }
}

// 重置当前方案
const resetCurrentSolution = () => {
  currentSolution.solutionId = ''
  currentSolution.solutionName = ''
  currentSolution.solutionCode = ''
  currentSolution.directoryId = currentCategoryId.value || ''
  currentSolution.applicableScenario = ''
  currentSolution.solutionContent = ''
  currentSolution.files = ''
  currentSolution.filesList = []
  fileList.value = []
}

// 处理对话框关闭
const handleDialogClose = () => {
  solutionFormRef.value?.resetFields()
  resetCurrentSolution()
}

// 显示方案详情
const showSolutionDetail = async (row) => {
  try {
    tableLoading.value = true
    const res = await getSolutionDetail(row.solutionId)
    Object.assign(currentSolution, res.data)
    detailDialogTitle.value = `方案详情 - ${currentSolution.solutionName}`
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取方案详情失败:', error)
    ElMessage.error('获取方案详情失败')
  } finally {
    tableLoading.value = false
  }
}

// 确认保存方案
const confirmSolution = async () => {
  try {
    await solutionFormRef.value.validate()

    if (solutionDialogTitle.value === '新增方案') {
      await addSolution(currentSolution)
      ElMessage.success('新增方案成功')
    } else {
      await updateSolution(currentSolution)
      ElMessage.success('修改方案成功')
    }

    solutionDialogVisible.value = false
    await fetchSolutionList()
  } catch (error) {
    console.error('保存方案失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 删除方案
// const deleteSolution = (row) => {
//   ElMessageBox.confirm(`确认删除方案 "${row.solutionName}" 吗?`, '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(async () => {
//     try {
//       await deleteSolution(row.solutionId)
//       ElMessage.success('删除成功')
//       await fetchSolutionList()
//     } catch (error) {
//       console.error('删除失败:', error)
//       ElMessage.error('删除失败')
//     }
//   }).catch(() => {
//     // 取消删除
//   })
// }

// 处理文件上传前检查
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.warning('文件大小不能超过10MB')
    return false
  }
  return true
}

// 处理文件变化
const handleFileChange = (file, files) => {
  fileList.value = files
}

// 处理导入文件变化
const handleImportFileChange = (file) => {
  importFile.value = file.raw
}

// 显示导入对话框
const showImportDialog = () => {
  importFileList.value = []
  importFile.value = null
  importDialogVisible.value = true
}


// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchSolutionList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchSolutionList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchSolutionList()
}

// 获取来源类型标签
const getSourceTypeLabel = (type) => {
  return sourceTypeMap[type] || type
}

// 获取分类名称
const getCategoryName = (id) => {
  const findCategory = (categories) => {
    for (const category of categories) {
      if (category.id === id) return category.name
      if (category.children && category.children.length > 0) {
        const result = findCategory(category.children)
        if (result) return result
      }
    }
    return ''
  }
  return findCategory(categoryTree.value) || ''
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + 'KB'
  } else {
    return (size / 1024).toFixed(2) + 'MB'
  }
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.tree-actions {
  display: flex;
  gap: 8px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  display: none;
}

.el-tree-node__content:hover .node-actions {
  display: inline-block;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.solution-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.file-item {
  margin-bottom: 8px;
}

.file-size {
  margin-left: 8px;
  color: #909399;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
}
</style>